package bootstrap

import (
	"context"
	"fmt"
	"log"
	"lzppp/internal/app/model"
	"lzppp/internal/pkg/utils"
	"sync"

	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitAll() {
	InitDB()
	InitMinio()
}

var DB *gorm.DB

// InitDB 初始化数据库
func InitDB() {
	d := AppConfig.Database
	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		d.User, d.Password, d.Url, d.Name)

	var err error
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatalln("数据库初始化失败: " + err.Error())
	}

	// 自动迁移
	if err := DB.AutoMigrate(&model.User{}, &model.Test{}); err != nil {
		log.Fatalln("数据库迁移失败: " + err.Error())
	}

	log.Println(d.Url, "数据库初始化成功")
}

var _ *minio.Client
var minioOnce sync.Once

// InitMinio 初始化MINIO
func InitMinio() {
	minioOnce.Do(func() {
		cfg := AppConfig.Minio

		client, err := minio.New(cfg.Endpoint, &minio.Options{
			Creds:  credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
			Secure: cfg.UseSSL,
		})
		if err != nil {
			log.Fatalln("MinIO初始化失败:", err)
		}

		ctx := context.Background()

		// 确保 bucket 存在
		exists, err := client.BucketExists(ctx, cfg.Bucket)
		if err != nil {
			log.Fatalln("检查Bucket失败:", err)
		}
		if !exists {
			err = client.MakeBucket(ctx, cfg.Bucket, minio.MakeBucketOptions{})
			if err != nil {
				log.Fatalln("创建Bucket失败:", err)
			}
		}

		_ = client

		// utils.MinioTool
		utils.MinioTool = &utils.MinioUtil{
			Client:     client,
			BucketName: cfg.Bucket,
			Ctx:        ctx,
		}

		log.Println(cfg.Endpoint, "MinIO初始化成功")
	})
}
